using System;
using System.Web;
using Microsoft.SharePoint;
using System.Diagnostics;
using CKS.EBE.API;

namespace CKS.EBE
{
	public class BlogContext
	{
		private BlogSettings _BlogSettings;
		private int? _TimeOffset;
		private bool? _BlogEnabledSite;
		private string _CurrentTheme;
		private static IUrlProvider _urlProvider;

		public static Guid BlogFeatureGUID = new Guid("BBE9DEF7-2FE9-A0B1-D7BB-AA128C837EBE");
		public static Guid BlogThemeFeatureGUID = new Guid("BBE9DEF7-2FE9-A0B1-D712-AA128C837EBE");
		public static Guid BlogLinkbackFeatureGUID = new Guid("174AC416-59EC-4D9A-9157-F981106B5EBE");

		public bool BlogEnabledSite
		{
			get
			{
				try
				{
					if (_BlogEnabledSite.HasValue) return _BlogEnabledSite.Value;

					if (SPContext.Current.Web == null) return false;

					_BlogEnabledSite = BlogEnabled(SPContext.Current.Web);

					return _BlogEnabledSite.Value;
				}
				catch (Exception ex)
				{
					Trace.WriteLine(ex);
					return false;
				}
			}
		}

		public static bool BlogEnabled(SPWeb oWeb)
		{
			try
			{
				if (oWeb == null || !oWeb.Exists) return false;
				if (oWeb.Features[BlogFeatureGUID] == null) return false;

				var bs = new BlogSettings(oWeb.Url);
				return bs.BlogExtensionsEnabled;
			}
			catch (Exception ex)
			{
				Debug.WriteLine(ex);
				return false;
			}
		}

		public virtual bool IsBlogOwner
		{
			get
			{
				return SPContext.Current.Web.UserIsWebAdmin;
			}
		}

		public virtual bool IsBlogContributor
		{
			get
			{
				SPWeb web = SPContext.Current.Web;
				try
				{
					return web.DoesUserHavePermissions((SPBasePermissions)SPPermissionGroup64.Contributor);
				}
				catch
				{
					SPList oPostList = Helper.GetListByFolderName(web, Localization.GetListName(Localization.BlogList.Posts, web.Language));
					return oPostList.DoesUserHavePermissions(SPBasePermissions.AddListItems);
				}
			}
		}

		public int ClientTimeZoneOffsetFromWeb
		{
			get
			{
				try
				{
					if (!_TimeOffset.HasValue)
					{
						HttpCookie oCookie = HttpContext.Current.Request.Cookies["CksEbeTZ"];
						if (oCookie != null)
						{
							int iWeb = SPContext.Current.Web.RegionalSettings.TimeZone.Information.DaylightBias;
							_TimeOffset = iWeb - int.Parse(oCookie.Value);
						}
						else
							_TimeOffset = 0;
					}
				}
				catch (Exception ex)
				{
					Debug.Write(ex);
					_TimeOffset = 0;
				}

				return _TimeOffset.Value;
			}
		}

		public DateTime ClientDateFromWebDate(DateTime webDate)
		{
			//return SPContext.Current.Web.RegionalSettings.TimeZone.LocalTimeToUTC(webDate).AddMinutes(ClientTimeZoneOffsetFromWeb);
			return webDate.AddMinutes(ClientTimeZoneOffsetFromWeb);
		}

		public BlogSettings Settings
		{
			get { if (_BlogSettings == null) _BlogSettings = new BlogSettings(); return _BlogSettings; }
		}

		public static BlogContext Current
		{
			get
			{
				try
				{
					var bc = (BlogContext)HttpContext.Current.Items["ebeBlogContext"];
					if (bc == null)
					{
						bc = new BlogContext();
						HttpContext.Current.Items["ebeBlogContext"] = bc;
					}

					return bc;
				}
				catch (Exception ex)
				{
					Trace.Write("Error in Get BlogContext: {0}" + ex);
					return null;
				}
			}
		}

		public IUrlProvider UrlProvider
		{
			get
			{
				if (_urlProvider == null)
				{
					try
					{
						string sProvider = System.Configuration.ConfigurationManager.AppSettings["CksBlogUrlProvider"];
						if (!string.IsNullOrEmpty(sProvider))
						{
							string[] arBits = sProvider.Split(new[] { ',' }, 2);
							_urlProvider = AppDomain.CurrentDomain.CreateInstanceAndUnwrap(arBits[0], arBits[1]) as IUrlProvider;
						}
						else
							_urlProvider = new DefaultUrlProvider();
					}
					catch (Exception ex)
					{
						Trace.WriteLine(ex);
						_urlProvider = new DefaultUrlProvider();
					}
				}

				return _urlProvider;
			}
		}

		public string BlogThemeVariation
		{
			get
			{
				HttpCookie oCookie = HttpContext.Current.Request.Cookies["ebeBlogThemeVariation"];

				string sVariation = (oCookie == null) ? "" : oCookie.Value;

				if (string.IsNullOrEmpty(sVariation))
					sVariation = Settings.BlogThemeVariation;

				if (string.IsNullOrEmpty(sVariation)) sVariation = "Default";

				return sVariation;
			}
		}

		/// <summary>
		/// if a theme was selected through the theme selector, it is stored here. otherwise null
		/// </summary>
		public static string SelectedBlogTheme { get; set; }

		public string BlogTheme
		{
			get
			{
				if (Current.Settings.ThemeSelectorEnabled)
				{
					// theme selector is enabled. use selected theme from url or selector
					if (!string.IsNullOrEmpty(HttpContext.Current.Request["theme"]))
					{
						_CurrentTheme = HttpContext.Current.Request["theme"];
					}
					else if (string.IsNullOrEmpty(SelectedBlogTheme) == false)
					{
						// if a theme was selected through the themeselector, use it
						_CurrentTheme = SelectedBlogTheme;
					}
				}

				if (!string.IsNullOrEmpty(_CurrentTheme)) return _CurrentTheme;

				if (string.IsNullOrEmpty(_CurrentTheme)) _CurrentTheme = Settings.BlogTheme;
				if (string.IsNullOrEmpty(_CurrentTheme)) _CurrentTheme = "Default";

				return _CurrentTheme;
			}
		}

		public static bool IsRequestForContentType(string sContentType)
		{
			try
			{
				SPContext context = SPContext.Current;
				if (string.IsNullOrEmpty(sContentType) || context.ListItem == null || context.ListItem["ContentTypeId"] == null)
				{
					return false;
				}

				string sContextContentTypeID = context.ListItem[SPBuiltInFieldId.ContentTypeId].ToString();
					// ContentType.Id.ToString().ToLower();
				Debug.WriteLine("ContentTypeID: " + sContextContentTypeID);

				string sPassedContentTypeID = string.Empty;
				// get contentType from web
            SPContentType contentType = context.Web.AvailableContentTypes[sContentType];
				if (contentType != null)
				{
					sPassedContentTypeID = contentType.Id.ToString().ToLower();
				}
				else
				{
					// get contentType from list
					contentType = context.List.ContentTypes[sContentType];
					if (contentType != null)
					{
						sPassedContentTypeID = contentType.Id.ToString().ToLower();
					}
					else
					{
						// check for wiki library
						SPList list = SPContext.Current.List;
						if (list.BaseTemplate == SPListTemplateType.WebPageLibrary)
						{
							sPassedContentTypeID = SPBuiltInContentTypeId.WikiDocument.ToString().ToLower();
						}
					}
				}

				Debug.WriteLine("ContentTypeID: " + sPassedContentTypeID);
				return sContextContentTypeID.StartsWith(sPassedContentTypeID);
			}
			catch (Exception ex)
			{
				Trace.WriteLine(ex);
				return false;
			}
		}
	}
}